package com.forg.mvc.core.factory;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

import com.forg.mvc.core.RequestID;
import com.forg.mvc.core.RequestMethodEnum;
import com.forg.mvc.core.RequestParam;
import com.forg.mvc.core.RequestWraper;

public class RequestWraperFactory {
    
    public static RequestWraper createRequest(HttpServletRequest r){
        
        RequestWraper requestWraper = new RequestWraper();
        
        //method
        RequestMethodEnum method = RequestMethodEnum.getMethod(r.getMethod());
        
        //path
        String path = r.getServletPath();
        if(StringUtils.isEmpty(path)){
            path = r.getPathInfo();
        }
        
        //paramter
        RequestParam requestParams = getParameterMap(r);
        
        //requestID
        RequestID id = new RequestID(method, path);

        requestWraper.request(r).method(method).path(path).param(requestParams).id(id);
        
        return requestWraper;
    }
    
    
    /**
     * 重复参数按默认原则获取（取第一个） 拼装称Map<String,String>
     * 获取所有重复参数：
     * 
     *  Map<String,String[]> m = r.getParameterMap();
        String [] ss = m.get(key);
     * @param r
     * @return
     */
    public static RequestParam getParameterMap(HttpServletRequest r){
        
        RequestParam parameter = new RequestParam();
        
        Enumeration<String> parameterNames = r.getParameterNames();
        
        while(parameterNames.hasMoreElements()){
            String key = parameterNames.nextElement();
            
            String value = r.getParameter(key);
            
            if(value != null && value.length() > 0){
                parameter.put(key, value);
            }
        }
        return parameter;
    }
    


}
